import { getToken, setToken, removeToken , setTimeStamp } from '@/utils/auth.js'
import { loginApi, getUserInfo } from '@/api/user.js'
import { getEmployeesApi } from '@/api/employees'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  // 修改token
  saveToken (state, payload) {
    state.token = payload
    setToken(payload)
    setTimeStamp()
  },
  // 退出登录
  delToken (state, payload) {
    state.token = null
    removeToken()
  },
  saveUserInfo(state,payload) {
    state.userInfo = payload
  },
  removeUserInfo(state) {
    state.userInfo ={}
  }
}
const actions = {
  async saveToken (context, payload) {
    try {
      let res = await loginApi(payload)
      context.commit('saveToken', res.data)
    } catch (err) {
      // console.dir(err);
      console.log(err.message)
      return Promise.reject(err)
    }
  },
  async getUserInfo(context) {
    const res = await getUserInfo() 
    // console.log(res);
    const baseRes = await getEmployeesApi(res.data.userId)
    // console.log(baseRes);
    const result = {...res.data,...baseRes.data}
    context.commit('saveUserInfo', result)
    // 为后面埋一个伏笔
    return result
  },
  logout(context) {
    context.commit('delToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
